import React, { useState, useEffect, useCallback, useRef } from 'react';
import type { ProColumns, ProTableProps } from '@ant-design/pro-table';
import { ProTable, MyProTableProps } from '@/components/KaiyaTable/index';
import { Button, Select, Modal, Tree, Input } from 'antd';
import { getLogsList, getTenantNameList } from '@/services/logs';
import { getMenuByScope } from '@/services/userControl';
import { FilterOutlined, PlusOutlined } from '@ant-design/icons';
import { formatTreeData } from '@/utils/tools';
const OperationLogs: React.FC = () => {
  const formRef = useRef<any>();
  const TableCustomDeploy = {
    componentName: 'customTable',
  };
  const [tenantSelect, settenantSelect] = useState([]);
  const [initFormData, setInitFormData] = useState({
    tenant: 0,
    menu: [],
  });
  const [treeModalVisible, settreeModalVisible] = useState<boolean | undefined>(
    false,
  );
  const [menuTreeData, setmenuTreeData] = useState<any[]>([]);
  const [checkedKeys, setcheckedKeys] = useState<React.Key[]>([]);
  const [checkedRows, setcheckedRows] = useState<any[]>([]);
  const [firstRequest, setfirstRequest] = useState(true);
  useEffect(() => {
    initPageData();
  }, []);

  const initPageData = async () => {
    const tenantSelect = await getTenantNameList();
    settenantSelect(tenantSelect.data);
    const resTenantId = tenantSelect.data[0].id;
    const res = await getTreeDataByTenantId(resTenantId);
    const menuIds = getAllTreeKeys(res.data).keys;
    console.log(resTenantId, res.data,menuIds);
    formRef.current.setFieldsValue({
      tenant: resTenantId,
      menu: '全选',
    });
    setcheckedKeys(menuIds);
    setfirstRequest(false);
    return {
      tenant: resTenantId,
      menu: menuIds,
    };
    // tenantChange(resTenantId, null);
  };
  const getTreeDataByTenantId = useCallback(async (id) => {
    let params = {
      contain: 1,
      idList: [id],
      idType: 1,
      scope: 0,
    };
    const res = await getMenuByScope(params);
    console.log(res)
    setmenuTreeData(formatTreeData(res.data));
    return res;
  }, []);
  const requestHandle = async (params: any) => {
    const res = await getLogsList(params);
    console.log(res);
    return res;
  };
  const tenantChange = (val: any, form: any) => {
    getTreeDataByTenantId(val);
    form && form.setFieldsValue({ tenant: val });
  };
  const modalOnOkHandle = async () => {
    if (checkedRows.length > 0) {
      let rowsByTitle = checkedRows
        .map((item: any) => {
          return item.title;
        })
        .filter(Boolean);
      console.log(rowsByTitle);
      formRef.current.setFieldsValue({
        menu: rowsByTitle.join('，'),
      });
      settreeModalVisible(false);
    }
  };
  const getAllTreeKeys = (treeData: any[]) => {
    let keysArr: string[] | number[] = [];
    let dataArr: any[] = [];
    const _addIDFunction = (_treeData: any[]) => {
      for (const item of _treeData) {
        keysArr.push(item.id);
        dataArr.push(item);
        if (item.children) {
          _addIDFunction(item.children);
        }
      }
    };
    _addIDFunction(treeData);
    return {
      keys: keysArr,
      nodes: dataArr,
    };
  };
  const getTableBasicDeploy = (): ProTableProps<any, any, any> => {
    const columns: ProColumns[] = [
      {
        dataIndex: 'index',
        title: '序号',
        valueType: 'indexBorder',
      },
      {
        title: '客户名称',
        dataIndex: 'tenant',
        // valueType: 'select',
        renderFormItem: (schema, config, form) => {
          // console.log(this, schema, config, form);

          return (
            <Select onChange={(val) => tenantChange(val, form)}>
              {tenantSelect.map((item) => (
                <Select.Option key={item.id} value={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select>
          );
        },
        hideInTable: true,
      },
      {
        title: '开始日期',
        dataIndex: 'startTime',
        valueType: 'date',
        hideInTable: true,
      },
      {
        title: '结束日期',
        dataIndex: 'endTime',
        valueType: 'date',
        hideInTable: true,
      },
      {
        title: '所属菜单',
        dataIndex: 'menu',
        renderFormItem: (schema, config, form) => {
          // console.log(this, schema, config, form);
          return (
            <Input
              placeholder="请选择"
              onClick={() => {
                settreeModalVisible(true);
              }}
            ></Input>
          );
        },
      },
      // {
      //   title: '所属系统',
      //   dataIndex: 'name4',
      //   valueType: 'text',
      //   hideInSearch: true,
      // },

      {
        title: '操作终端',
        dataIndex: 'source',
        valueType: 'text',
        hideInTable: true,
      },
      {
        title: '操作人',
        dataIndex: 'operator',
        valueType: 'text',
      },
      {
        title: '操作内容',
        dataIndex: 'operation',
        valueType: 'text',
      },
      {
        title: '操作时间',
        dataIndex: 'updatedTime',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: 'IP地址',
        dataIndex: 'ip',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '请求参数',
        dataIndex: 'requestData',
        valueType: 'text',
        hideInSearch: true,
      },
      {
        title: '响应状态',
        dataIndex: 'responseStatus',
        valueType: 'text',
        hideInSearch: true,
      },
    ];
    const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any[]) => {},
      getCheckboxProps: (record: any) => ({
        disabled: false,
        name: record.name,
      }),
    };
    return {
      columns,
      formRef,
      search: {
        collapsed: false,
      },
      request: async (params = {}, sort, filter) => {
        console.log('request请求发出', params, firstRequest);
        let menu = params.menu && params.menu === '全选' ? { menu: checkedKeys } : {};
        if (firstRequest) {
          const res = await initPageData();
          params.tenant = res.tenant;
          menu = { menu: res.menu };
        }
        let startTime = params.startTime
          ? { startTime: new Date(params.startTime).getTime() }
          : {};
        let endTime = params.endTime
          ? { endTime: new Date(params.endTime).getTime() }
          : {};

        let lastParams = {
          ...params,
          ...startTime,
          ...endTime,
          ...menu,
          pageNumber: params.current,
          pageSize: params.pageSize,
        };
        delete lastParams.current;
        delete lastParams.createdTime;
        console.log(lastParams);
        return requestHandle(lastParams);
      },
      rowSelection: {
        type: 'checkbox',
        ...rowSelection,
      },
      pagination: {
        pageSize: 5,
      },
      rowKey: 'id',
    };
  };

  const jsonOption: MyProTableProps = {
    TableCustomDeploy,
    TableBasicDeploy: getTableBasicDeploy,
  };
  return (
    <div>
      <Modal
        title="系统菜单"
        visible={treeModalVisible}
        onOk={modalOnOkHandle}
        onCancel={() => {
          settreeModalVisible(false);
        }}
      >
        <Tree
          style={{ maxHeight: '50vh', overflowY: 'auto' }}
          checkable
          autoExpandParent={true}
          checkedKeys={checkedKeys}
          onCheck={(checkedKeysValue: any, checkedRow: any) => {
            console.log(checkedKeysValue, checkedRow);
            setcheckedKeys(checkedKeysValue);
            setcheckedRows(checkedRow.checkedNodes);
          }}
          treeData={menuTreeData}
        />
      </Modal>
      <ProTable {...jsonOption}></ProTable>
    </div>
  );
};

export default OperationLogs;
